# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class FapiaoPaperLine(models.Model):
    _name = 'fp.fapiao.paper.line'
    _description = 'Fapiao Line'
    _order = 'fapiao_id, sequence, id'

    fapiao_id = fields.Many2one(
        'fp.fapiao.paper', 'Fapiao',
        required=True, ondelete='cascade', index=True, copy=False)

    company_id = fields.Many2one(related='fapiao_id.company_id')
    type = fields.Selection(related='fapiao_id.type')
    invoice_type = fields.Selection(related='fapiao_id.invoice_type')
    state = fields.Selection(related='fapiao_id.state')

    line_type = fields.Selection(
        selection=[
            ('line', 'Line'),
            ('discount', 'Discount'),
        ], string='Line Type',
        required=True, index=True,
        default='line',
        help="折扣行?=无价格无数量? 必须紧挨着上一行, 同商品(规格单位可空). 逆否命题是否成立.")

    name = fields.Char('Label')
    sequence = fields.Integer('Sequence', default=10)
    row_number_check = fields.Integer(
        'Row Number Check', default=0, help='查验结果, 返回的行号')

    row_number = fields.Integer('Row Number', default=0)
    ref_row_number = fields.Integer(
        'Ref Row Number', default=0, help='若为折扣行, 该字段存储对应被折扣行 row_number')

    product_id = fields.Many2one(
        'fp.product', 'Fapiao Product', required=True, index=True)

    vat_product_id = fields.Many2one(
        string='Var Product', related='product_id.vat_product_id')

    vat_product_code = fields.Char(
        'Var Product Code', related='product_id.vat_product_code')
    vat_product_name = fields.Char(
        'Var Product Name', related='product_id.vat_product_name')

    product_code = fields.Char('Product code', related='product_id.code')
    product_name = fields.Char('Product Name', related='product_id.name')
    product_spec = fields.Char('Spec', related='product_id.spec')
    product_uom = fields.Char('Uom', related='product_id.uom')

    tax_ratio = fields.Float('Tax Ratio', help="仅仅是发票上的一个文本, 13%")

    quantity = fields.Float('Quantity', required=True, default=1.0)
    amount_untaxed = fields.Float('Untaxed Amount')
    amount_tax = fields.Float('Tax')
    amount_total = fields.Float('Total', help="非票面信息")
    price_untax = fields.Float('Unit Price Untax')
    price_unit = fields.Float('Unit Price', help="非票面信息")

    # 进项票, quantity, amount_untaxed, amount_tax => amount_total, price_untax, price_unit
    # 进项票, 查验完成后, 在查验接口中完成计算 todo test

    # 销项开票, 销售行, quantity, price_unit => amount_total, price_untax
    # 销项开票, 销售行, amount_total, tax_ratio => amount_untaxed, amount_tax
    # 销项开票, 折扣行, amount_total, tax_ratio => amount_untaxed, amount_tax
    # 销项开票查询后, quantity, amount_untaxed, amount_tax => amount_total, price_untax, price_unit
    # 销项开票查询后, 在查验接口中完成计算 todo test

    _sql_constraints = [
        ('row_number_unique', 'unique(row_number, fapiao_id)',
         'Row Number Unique of one Fapiao.')]
